import 'package:enjoy_plus/models/add_house.dart';
import 'package:enjoy_plus/models/house/house_detail.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';

class HouseDetail extends StatefulWidget {
  const HouseDetail({super.key, required this.id});
  final String id;

  @override
  State<HouseDetail> createState() => _HouseDetailState();
}

class _HouseDetailState extends State<HouseDetail> {
  bool isLoading = true;
  // 审核状态1审核中2审核成功3审核失败
  final statusColors = [
    Colors.blue,
    Colors.green,
    Colors.red,
  ];

  final statusBGColors = [
    Colors.blue.withOpacity(0.2),
    Colors.green.withOpacity(0.2),
    Colors.red.withOpacity(0.2),
  ];

  final statusTexts = [
    '审核中',
    '已绑定',
    '审核失败',
  ];

  HouseDetailData? _houseDetail;

  Future<void> getHouseDetail() async {
    setState(() => isLoading = true);
    ToastUtil.showSuccess('获取详情');
    try {
      final res = await http.get<HouseDetailData>(
        '/room/${widget.id}',
        fromJson: (json) => HouseDetailData.fromJson(json),
      );
      if (res.code == 10000) {
        setState(() {
          _houseDetail = res.data;
          isLoading = false;
        });
      } else {
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      ToastUtil.showError(e.toString());
      setState(() => isLoading = false);
    }
  }

  //删除房屋
  Future<void> removeHouse() async {
    ///room/{id} 删除房屋
    try {
      final res = await http.delete<AddHouseData>(
        '/room/${widget.id}',
        fromJson: (json) => AddHouseData.fromJson(json),
      );
      if (res.code == 10000) {
        ToastUtil.showSuccess('删除成功');
        Navigator.pop(context);
        eventBus.fire(RefreshRoomList());
      } else {
        ToastUtil.showError(res.message);
        Navigator.pop(context);
        eventBus.fire(RefreshRoomList());
      }
    } catch (e) {
      ToastUtil.showError(e.toString());
      eventBus.fire(RefreshRoomList());
    }
  }

  @override
  void initState() {
    super.initState();
    getHouseDetail();
    eventBus.on<RefreshHouseDetail>().listen((event) {
      getHouseDetail();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('房源详情'),
        backgroundColor: const Color(0xFFF1F2F6),
        centerTitle: true,
        leading: IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(Icons.arrow_back_ios)),
      ),
      body: Container(
        color: const Color(0xFFF1F2F6),
        child: isLoading
            ? const Center(child: CircularProgressIndicator(color: Colors.blue))
            : Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Padding(
                            padding: EdgeInsets.all(12),
                            child: Text('房屋信息',
                                style: TextStyle(color: Colors.black45)),
                          ),
                          Container(
                            padding: const EdgeInsets.all(12),
                            color: Colors.white,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                    '${_houseDetail?.point}${_houseDetail?.building}',
                                    style: const TextStyle(
                                        fontSize: 14, color: Colors.black87)),
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: statusBGColors[
                                        (_houseDetail?.status.toInt() ?? 0) -
                                            1],
                                    borderRadius: BorderRadius.circular(5),
                                  ),
                                  child: Text(
                                      statusTexts[
                                          (_houseDetail?.status.toInt() ?? 0) -
                                              1],
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500,
                                          color: statusColors[
                                              (_houseDetail?.status.toInt() ??
                                                      0) -
                                                  1])),
                                )
                              ],
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.all(12),
                            child: Text('业主信息',
                                style: TextStyle(color: Colors.black45)),
                          ),
                          //房间号
                          Container(
                            padding: const EdgeInsets.all(12),
                            color: Colors.white,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Expanded(flex: 1, child: Text('房间号')),
                                Expanded(
                                    flex: 4,
                                    child: Text(
                                        '${_houseDetail?.building}${_houseDetail?.room}')),
                              ],
                            ),
                          ),
                          //业主
                          Container(
                            padding: const EdgeInsets.all(12),
                            color: Colors.white,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Expanded(flex: 1, child: Text('业主')),
                                Expanded(
                                    flex: 4,
                                    child: Text(_houseDetail?.name ?? '')),
                              ],
                            ),
                          ),
                          //手机号
                          Container(
                            padding: const EdgeInsets.all(12),
                            color: Colors.white,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Expanded(flex: 1, child: Text('手机号')),
                                Expanded(
                                    flex: 4,
                                    child: Text(_houseDetail?.mobile ?? '')),
                              ],
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.all(12),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('本人身份证照片',
                                    style: TextStyle(color: Colors.black45)),
                              ],
                            ),
                          ),
                          //人像面照片
                          Container(
                            padding: const EdgeInsets.all(12),
                            width: double.infinity,
                            height: 240,
                            color: Colors.white,
                            child: Image.network(
                              _houseDetail?.idcardFrontUrl ?? '',
                              fit: BoxFit.contain,
                            ),
                          ),
                          const SizedBox(height: 12),
                          //国徽面照片
                          Container(
                            padding: const EdgeInsets.all(12),
                            width: double.infinity,
                            height: 240,
                            color: Colors.white,
                            child: Image.network(
                              _houseDetail?.idcardBackUrl ?? '',
                              fit: BoxFit.contain,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  // 底部按钮
                  Container(
                    padding: const EdgeInsets.all(12),
                    color: Colors.white,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        ElevatedButton(
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                      title: const Text('提示'),
                                      content: const Text('确定删除该房屋吗？'),
                                      actions: [
                                        TextButton(
                                            onPressed: () =>
                                                Navigator.pop(context),
                                            child: const Text('取消')),
                                        TextButton(
                                            onPressed: () => removeHouse(),
                                            child: const Text('确定')),
                                      ],
                                    ));
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.white,
                            foregroundColor: Colors.red,
                          ),
                          child: const Row(
                            children: [
                              Icon(Icons.delete, color: Colors.red),
                              Text('删除房屋', style: TextStyle(color: Colors.red)),
                            ],
                          ),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            Navigator.pushNamed(context, '/addHouseFrom',
                                arguments: {
                                  'id': widget.id,
                                  'isEdit': true,
                                  'community': _houseDetail?.point,
                                  'building': _houseDetail?.building,
                                  'room': _houseDetail?.room,
                                });
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.white,
                            foregroundColor: Colors.blue,
                          ),
                          child: const Row(
                            children: [
                              Icon(Icons.edit, color: Colors.blue),
                              Text('修改房屋',
                                  style: TextStyle(color: Colors.blue)),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}
